package cn.itcast.bos.web.action.base;

import java.util.Collection;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.service.base.FixedAreaService;
import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class FixedAreaAction extends BaseAction<FixedArea> {
	
	
	// 调用业务层
	@Autowired
	private FixedAreaService fixedAreaService;

	// 带条件分页显示方法
	@Action(value = "fixedArea_pageQuery", results = { @Result(name = "success", type = "json") })
	public String findByParams() {
		// 分页基本查询对象
		Pageable pageable = new PageRequest(page-1, rows);
		
		// 待条件的分页查询对象
		Specification<FixedArea> specification = new Specification<FixedArea>() {

			@Override
			public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				
			Predicate predicate = null;
				 //获取所有条件对象
				 if(StringUtils.isNotBlank(model.getId())){
				 Predicate p1 =
				 cb.equal(root.get("id").as(String.class),model.getId());
				 predicate = cb.and(p1);
				 }
				 if(StringUtils.isNotBlank(model.getCompany())){
				 Predicate p2 =
				 cb.like(root.get("company").as(String.class),"%"+model.getCompany()+"%");
				 predicate = cb.and(p2);
				 }
//				 Join<Object, Object> standardRoot = root.join("subareas",
//				 JoinType.INNER);
//				 if(model.getSubareas()!=null&&StringUtils.isNotBlank(model.getSubareas())){
//				 Predicate p3 =
//				 cb.like(root.get("subareaName").as(String.class),model.getCompany());
//				 list.add(p3);
				 //}

				return predicate;
			}

		};
		Page<FixedArea> pagedate = fixedAreaService.findByParams(specification, pageable);
		
		pushPageDataToValueStack(pagedate);

		return SUCCESS;

	}

	// 直接添加定区方法
	@Action(value = "fixedArea_save", results = {
			@Result(name = "success", type = "redirect", location = "./pages/base/fixed_area.html") })
	public String saveFixedArea() {
		fixedAreaService.saveFixedArea(model);
		return SUCCESS;
	}
	//定区查找未关联的客户
	@Action(value="fixedArea_findNoAssociationCustomers",results={@Result(name="success",type="json")})
	public String findNOAssociationCustomers(){
		//通过网络获取客户信息集合，数据形式为json
		Collection<? extends Customer> collection = WebClient.create("http://localhost:8083/crm_management/services/customerService/noassociationcustomers").
				accept(MediaType.APPLICATION_JSON).getCollection(Customer.class);
		//将数据压入值栈的顶部
		ActionContext.getContext().getValueStack().push(collection);
		return SUCCESS;
	}
	//定区根据定区id查找客户关联客户
		@Action(value="fixedArea_findHasAssociationFixedAreaCustomers",results={@Result(name="success",type="json")})
		public String findHasAssociationFixedAreaCustomers(){
			//通过网络获取客户信息集合，数据形式为json
			System.out.println("http://localhost:8083/crm_management/services/customerService/associationfixedareacustomers/"+model.getId());
			Collection<? extends Customer> collection = WebClient.create("http://localhost:8083/crm_management/services/customerService/associationfixedareacustomers/"+model.getId()).
					accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).getCollection(Customer.class);
			//将数据压入值栈的顶部
			ActionContext.getContext().getValueStack().push(collection);
			return SUCCESS;
		}
    //定区关联客户
		 //属性驱动获取客户id
		private String[] customerIds;

		public void setCustomerIds(String[] customerIds) {
			this.customerIds = customerIds;
		}
		@Action(value="fixedArea_associationCustomerToFixedArea",results={@Result(name="success",type="redirect",location="./pages/base/fixed_area.html")})
		public String  associationCustomerToFixedArea(){
			//通过网络获取客户信息集合，数据形式为json
			//将所有需要关联的客户id拼接
			String customerIdStr = StringUtils.join(customerIds,",");
			System.out.println(customerIdStr);
			WebClient.create("http://localhost:8083/crm_management/services/customerService/associationCustomersToFixedArea?customerIdStr="
			+customerIdStr+"&fixedAreaId="+model.getId())
			.put(null);
			return SUCCESS;
		}
		//定区关联快递员（排班）
		  //属性驱动获取快递员id和排班id
		private Integer courierId;
		private Integer takeTimeId;
		
		public void setCourierId(Integer courierId) {
			this.courierId = courierId;
		}

		public void setTakeTimeId(Integer takeTimeId) {
			this.takeTimeId = takeTimeId;
		}
		@Action(value="fixedArea_associationCourierToFixedArea",results={@Result(name="success",type="redirect",location="./pages/base/fixed_area.html")})
		public String associationCourierToFixedArea(){
			System.out.println(model.getId());
			fixedAreaService.associationCourierToFixedArea(model,courierId,takeTimeId);
			return SUCCESS;
			
		}
}
